<?php
include_once 'DBConn.php';
 
abstract class BaseM {
	
	public static $dbConn;
	protected $log;
	
	function __construct($account=DB_USER, $password=DB_PASSWORD, $database=DB_DATABASE) {
		if (BaseM::$dbConn== null) {
			BaseM::$dbConn = new DBConn ($account, $password, $database);
		}
	}
		
	protected function querySQL($sql, $isSingle=false) {
		$result = @mysql_query($sql);
	    $ret =  $this->toArray($result, true);
	    if ($isSingle) {
	    	if (count($ret) > 0) {
	    		return  $ret[0];	
	    	} else {
	    		return null;
	    	}
	    		
	    } else {
		    return $ret;	
	    }
	}
	
	protected function toArray($result, $isObj = true) {
		$row_set = array ();
		if ($isObj) {
			while ( $row = @mysql_fetch_object ( $result ) ) {
				$row_set [] = $row;
			}
		} else {
			while ( $row = @mysql_fetch_row ( $result ) ) {
				$row_set [] = $row;
			}
		}
		@mysql_free_result ( $result );
		
		return $row_set;
	}
	 
	
	protected function genInserSQL($tableName, $obj) {
		$sql = "insert into $tableName ";
		$field = "";
		$val = "";
		foreach ( $obj as $key => $value ) {
			if ("Pid" != $key) {
				$field .= "$key,";
				
				if (is_string ( $value )) {
					$val .= "'" . $value . "',";
				} else {
					$val .= $value . ",";
				}
			}
		}
		return $sql .= "(" . substr ( $field, 0, strlen ( $field ) - 1 ) . ") values (" . substr ( $val, 0, strlen ( $val ) - 1 ) . ")";
	}
	
	 function genUpdateSQL($tableName, $obj, $whereKey) {
		$sql = "UPDATE $tableName SET ";
		$str="";
		$whereValue= array();
		
		foreach ( $obj as $key => $value ) {
			$str .= $key."='".$value."',";
		}
		
		$where = " WHERE 1=1 ";
		
		if ($where != null) {
			$arr = (array)$obj;
			foreach($whereKey as $val) {
				$where.= " AND $val = '$arr[$val]'" ;
			}
		}
		
		return $sql .= substr ( $str, 0, strlen ( $str ) - 1 ).$where;
	}
	 
	protected function open() {
		BaseM::$dbConn->open ();
	}
	
	protected function close() {
		//BaseM::$dbConn->close ();
	}
	
	 function __destruct() {
		//$this->close ();
	}
}
?>